<template>
  <div class="product-container">
    <div class="search-bar">
      <el-input
        v-model="searchForm.name"
        placeholder="请输入商品名称"
        style="width: 200px"
      />
      <el-button type="primary" @click="loadData">查找</el-button>
      <el-button type="primary" @click="handleAdd">添加</el-button>
      <el-button type="danger" @click="showDeleteByNameDialog">按名称删除</el-button>
    </div>

    <el-table :data="tableData" border style="width: 100%" height="calc(100% - 100px)">
      <el-table-column prop="productId" label="ID" width="80" />
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="category" label="商品类别" />
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="stock" label="库存">
        <template #default="scope">
          <span :style="{ color: scope.row.stock === 0 ? 'red' : 'inherit' }">
            {{ scope.row.stock }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            修改
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="form.productId ? '修改商品' : '添加商品'"
      width="500px"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="商品类别" prop="category">
          <el-input v-model="form.category" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" :precision="2" :step="0.1" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="form.stock" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="deleteByNameDialogVisible"
      title="按名称删除商品"
      width="400px"
    >
      <el-form :model="deleteForm" label-width="100px">
        <el-form-item label="商品名称">
          <el-input v-model="deleteForm.name" placeholder="请输入要删除的商品名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteByNameDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleDeleteByName">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const searchForm = reactive({
  name: ''
})
const form = reactive({
  productId: null,
  name: '',
  category: '',
  price: 0,
  stock: 0
})
const deleteByNameDialogVisible = ref(false)
const deleteForm = reactive({
  name: ''
})
const formRef = ref(null)

const rules = reactive({
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请输入商品类别', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存必须大于等于0', trigger: 'blur' }
  ]
})

const loadData = async () => {
  try {
    const res = await axios.get('http://localhost:8080/product/page', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        name: searchForm.name
      }
    })
    if (res.data.code === 200) {
      tableData.value = res.data.data.records
      total.value = res.data.data.total
    } else {
      ElMessage.warning(res.data.message)
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error('加载数据失败')
    tableData.value = []
    total.value = 0
  }
}

const resetForm = () => {
  form.productId = null
  form.name = ''
  form.category = ''
  form.price = 0
  form.stock = 0
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
  nextTick(() => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
  })
}

const handleEdit = (row) => {
  form.productId = row.productId
  form.name = row.name
  form.category = row.category
  form.price = row.price
  form.stock = row.stock

  dialogVisible.value = true
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除商品《'+row.name+'》吗？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(async () => {
      try {
        const res = await axios.delete(
          `http://localhost:8080/product/${row.productId}`
        )

        if (res.data.code === 200) {
          ElMessage.success(res.data.data)
          loadData()
        } else {
          ElMessage.error(res.data.message)
        }
      } catch (error) {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}

const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    const url = form.productId
      ? 'http://localhost:8080/product'
      : 'http://localhost:8080/product'
    const method = form.productId ? 'put' : 'post'
    const res = await axios[method](url, form)
    if (res.data.code === 200) {
      ElMessage.success(res.data.data)
      dialogVisible.value = false
      loadData()
    } else {
      ElMessage.error(res.data.message)
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('操作失败')
    }
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadData()
}

const showDeleteByNameDialog = () => {
  deleteForm.name = ''
  deleteByNameDialogVisible.value = true
}

const handleDeleteByName = async () => {
  if (!deleteForm.name) {
    ElMessage.warning('请输入商品名称')
    return
  }

  try {
    const res = await axios.delete(`http://localhost:8080/product/name/${deleteForm.name}`)
    debugger
    if (res.data.code === 200) {
      ElMessage.success(res.data.data)
      deleteByNameDialogVisible.value = false
      loadData()
    } else {
      ElMessage.error(res.data.message)
    }
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.product-container {
  position: absolute;
  top: 20px;
  left: 20px;
  right: 20px;
  bottom: 20px;
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.search-bar {
  padding-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.el-table {
  flex: 1;
  overflow: hidden;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

:deep(.el-table__fixed-right) {
  height: 100% !important;
}

.pagination {
  padding-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__body) {
  padding: 20px 40px;
}
</style>
